package com.kuang.tree;

/*  给你一棵二叉树的根节点 root ，返回其节点值的 后序遍历 。    */

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author kjx
 */
public class PostorderTraversal {

    //第一种还是递归
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        getAnswer(result, root);
        return result;
    }

    private void getAnswer(List<Integer> result, TreeNode root) {
        if (root == null) {
            return;
        }
        getAnswer(result, root.left);
        getAnswer(result, root.right);
        result.add(root.val);
    }


    //后序遍历的用栈实现
    //这里必须要多加一个指针来记录上一次访问的节点，因为从左到右必须要经过父亲节点
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode preNode = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == preNode) {
                result.add(root.val);
                preNode = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }
        return result;
    }
}
